import { BetaSchemaForm } from "@ant-design/pro-form";
import { PageContainer } from "@ant-design/pro-layout";
import { useAxiosGet, useAxiosPost, useLocation } from "@sker/sdk"
import { renderAdminPage, useWebSocket } from "@sker/ui"
import { useEffect, useState } from "react";
import CodeMirror from '@uiw/react-codemirror';
import { javascript } from '@codemirror/lang-javascript';

import { Alert, Button, Form, Input, Tag } from "antd";
const utilsMethod = ['clickButton',
    'clickButtonRect',
    'configTokenFactory',
    'formatTime',
    'generateRandomString',
    'getCheckable',
    'getClickable',
    'getCurrentViewNode',
    'getCurrentViewNodes',
    'getDisplaySize',
    'getTokenDefault',
    'isInCurrentView',
    'parseJson',
    'tryGet',
    'tryGetAll',
    'tryGetSafe']
const tokensMethods = ['ACCOUNT_NAME',
    'ACTION_CONFIG_GET',
    'ACTION_LOG',
    'ACTION_RUN_COMMAND',
    'APP',
    'APPLICATION_INITIALIZATION',
    'APP_TITLE',
    'CALL_WEB',
    'CLOUD_CODE',
    'CLOUD_CODE_ERROR',
    'CLOUD_CODE_FINISH',
    'CLOUD_CODE_RETURN',
    'CLOUD_HOST',
    'CLOUD_JS_BRIDGE_CALL_HANDLER',
    'CLOUD_JS_BRIDGE_REGISTER_HANDLER',
    'CLOUD_PORT',
    'CLOUD_WEBVIEW_URL',
    'CLOUD_WS',
    'COMMAND_CLEAR_CACHE',
    'COMMAND_EXIT',
    'COMMAND_LOGIN',
    'COMMAND_LOGIN_SUCCESS',
    'COMMAND_UPDATE_DEVICE_SETTING',
    'CONFIG',
    'CURRENT_ACTIVITY',
    'CURRENT_PACKAGE',
    'CURRENT_TASK',
    'DEVICE_NAME',
    'DEVICE_SETTING',
    'DEVICE_UUID',
    'HTTP_GET',
    'HTTP_POST',
    'KWAI_PACKAGE',
    'LISTENERS',
    'NOTIFICATION_LISTENER',
    'ON_DESTORY',
    'ON_INITS',
    'PUSH_TOKEN',
    'SENDER',
    'SHOW_CONSOLE',
    'STATE_CHANGE',
    'STATUS_BAR_COLOR',
    'TASK',
    'TOAST_LISTENER',
    'TOKEN',
    'TOOLBAR_BG_COLOR',
    'WS_CONNECT',
    'currentActivityIn',
    'currentActivityIs',
    'currentPackageIn',
    'currentPackageIs',
    'getAccountName',
    'getAllListener',
    'getAllOnDestory',
    'getAllOnInit',
    'getAppTitle',
    'getApps',
    'getCallWeb',
    'getCloudHost',
    'getCloudPort',
    'getCloudWs',
    'getConfig',
    'getCurrentActivity',
    'getCurrentPackage',
    'getCurrentTask',
    'getDeviceName',
    'getDeviceSetting',
    'getDeviceUuid',
    'getHttpGet',
    'getHttpPost',
    'getNotificationListeners',
    'getPushToken',
    'getSender',
    'getShowConsole',
    'getStatusBarColor',
    'getTask',
    'getToastListeners',
    'getToken',
    'getToolbarBgColor',
    'registerHandler']
export const ScriptEditPage: React.FC<{}> = ({ }) => {
    const location = useLocation()
    const id = location.searchParams.get('id');
    const type = location.searchParams.get('type')
    const { data: scriptDetail, fetch: fetchScriptDetail } = useAxiosGet(`autojs/core/web/script/scriptGet`)
    const { data: scriptSave, fetch: fetchScriptSave } = useAxiosPost(`autojs/core/web/script/scriptsave`)
    const { data: runData, fetch: fetchScriptRun } = useAxiosPost(`autojs/core/web/script/scriptRun`)
    const { data: runDatas, fetch: fetchScriptRuns } = useAxiosPost(`autojs/core/web/script/scriptRuns`)


    const { latestMessage, connect } = useWebSocket('autojs/core/web/ws?uuid=RUN_DEBUG_SCRIPT', {})
    const [form] = Form.useForm()
    useEffect(() => {
        const debugDeviceUuid = localStorage.getItem(`debugDeviceUuid`) || `svMSV55WrfvWKCgw`
        fetchScriptDetail({ id, type }).then(res => {
            form.setFieldsValue({ ...res.data, debugDeviceUuid })
        })
        connect()
    }, [])

    const [returnData, setReturnData] = useState<string>(``)
    const [logData, setLogData] = useState<string[]>([])
    const [errData, setErrData] = useState<string>(``)

    useEffect(() => {
        if (!latestMessage) return;
        const result = JSON.parse(latestMessage.data)
        const { data, type, uuid, log, id } = result;
        if (type === "CLOUD_CODE_RETURN") {
            setReturnData(JSON.stringify(data, null, 2))
        }
        if (type === "CLOUD_CODE_FINISH") {

        }
        if (type === "CLOUD_CODE_ERROR") {
            setErrData(JSON.stringify(data, null, 2))
        }
        if (type === "CLOUD_DEBUG") {
            setErrData(JSON.stringify(data, null, 2))
            log && setLogData((pre) => ([...pre, log]))
        }
    }, [latestMessage]);


    return <PageContainer>
        <code className="px-12px py-8px">
            {logData.map((txt, index) => {
                return <div key={index}>{txt}</div>
            })}
        </code>
    </PageContainer >
}

renderAdminPage(ScriptEditPage, 'autojs/core/web/scriptEdit')
